package com.example.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.dto.*;
import com.example.entity.AirspaceNormsAndConstraints;
import com.example.entity.AirspaceNormsAndConstraintsMini;
import com.example.mapper.AirspaceNormsAndConstrainsMapper;
import com.example.util.OSSUtil;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


@Service
public class AirspaceNormsAndConstraintsService {
    @Autowired
    private AirspaceNormsAndConstrainsMapper airspaceNormsAndConstrainsMapper;
    //根据id查询
    public Optional<AirspaceNormsAndConstraints> getById(Integer id) {
        AirspaceNormsAndConstraints airspaceNormsAndConstraints = airspaceNormsAndConstrainsMapper.selectById(id);
        if(airspaceNormsAndConstraints == null){
            return Optional.empty();
        }
        return Optional.of(airspaceNormsAndConstraints);
    }
    //新分页查询
    public AirspaceNormsAndConstraintsPageQueryBDTO<AirspaceNormsAndConstraintsMini> page(AirspaceNormsAndConstraintsPageQueryDTO airspaceNormsAndConstraintsPageQueryDTO) {
        int currentPage = airspaceNormsAndConstraintsPageQueryDTO.getCurrentPage();
        int size = airspaceNormsAndConstraintsPageQueryDTO.getSize();
        String order = airspaceNormsAndConstraintsPageQueryDTO.getOrder();
        String title = airspaceNormsAndConstraintsPageQueryDTO.getTitle();
        Integer informationCategory = airspaceNormsAndConstraintsPageQueryDTO.getInformationCategory();
        Integer informationSources =  airspaceNormsAndConstraintsPageQueryDTO.getInformationSources();

        QueryWrapper<AirspaceNormsAndConstraints> queryWrapper = new QueryWrapper<>();
        if (title != null && !title.isEmpty()) {
            queryWrapper.lambda().like(AirspaceNormsAndConstraints::getTitle, title);
        }
        if (informationCategory != null) {
            queryWrapper.and(e->e.lambda().eq(AirspaceNormsAndConstraints::getInformationCategory, informationCategory));
        }
        if (informationSources != null) {
            queryWrapper.and(e->e.lambda().eq(AirspaceNormsAndConstraints::getInformationSources, informationSources));
        }

        // 根据排序规则决定是按时间最新（降序）还是最晚（升序）
        if ("时间最新".equals(order)) {
            queryWrapper.orderByDesc("publication_time");
        } else if ("时间最晚".equals(order)) {
            queryWrapper.orderByAsc("publication_time");
        }
// 执行分页查询
        Page<AirspaceNormsAndConstraints> page = new Page<>(currentPage, size);
        Page<AirspaceNormsAndConstraints> airspaceNormsAndConstrainsSearchPage = airspaceNormsAndConstrainsMapper.selectPage(page,queryWrapper);
        //搜索后数据处理
        int total = (int) airspaceNormsAndConstrainsSearchPage.getTotal();
        int pageSize = (int)page.getSize();

        List<AirspaceNormsAndConstraintsMini> airspaceNormsAndConstraintsMinis = new ArrayList<>();
        AirspaceNormsAndConstraintsPageQueryBDTO<AirspaceNormsAndConstraintsMini> airspaceNormsAndConstraintsPageQueryBDTO = new AirspaceNormsAndConstraintsPageQueryBDTO<>();

        // 将查询结果转换为 BDTO
        for (AirspaceNormsAndConstraints demand : airspaceNormsAndConstrainsSearchPage.getRecords()) {
            AirspaceNormsAndConstraintsMini airspaceNormsAndConstraintsMini = new AirspaceNormsAndConstraintsMini();
            airspaceNormsAndConstraintsMini.setId(demand.getId());
            airspaceNormsAndConstraintsMini.setTitle(demand.getTitle());
            airspaceNormsAndConstraintsMini.setPublicationTime(demand.getPublicationTime());
            airspaceNormsAndConstraintsMini.setInformationSource(demand.getInformationSources());
            airspaceNormsAndConstraintsMini.setInformationCategory(demand.getInformationCategory());
            airspaceNormsAndConstraintsMinis.add(airspaceNormsAndConstraintsMini);
        }
        airspaceNormsAndConstraintsPageQueryBDTO.setTotal(total);
        airspaceNormsAndConstraintsPageQueryBDTO.setPageData(airspaceNormsAndConstraintsMinis);
        airspaceNormsAndConstraintsPageQueryBDTO.setPageNum(currentPage);
        airspaceNormsAndConstraintsPageQueryBDTO.setPageSize(size);
        Integer pages = (int) Math.ceil((double) total / pageSize);//计算搜寻关键字后的数据总页数
        airspaceNormsAndConstraintsPageQueryBDTO.setPages(pages);
        return airspaceNormsAndConstraintsPageQueryBDTO;
    }
    public Optional<AirspaceNormsAndConstraintsInformationExtractionBDTO> informationExtraction(Integer id) {
        AirspaceNormsAndConstraints airspaceNormsAndConstraints = airspaceNormsAndConstrainsMapper.selectById(id);
        AirspaceNormsAndConstraintsInformationExtractionBDTO airspaceNormsAndConstraintsInformationExtractionBDTO = new AirspaceNormsAndConstraintsInformationExtractionBDTO();
        String website = airspaceNormsAndConstraints.getPdfUrl();
        if (website!=null&& !website.isEmpty()) {
            System.out.println("website:"+website);
            airspaceNormsAndConstraintsInformationExtractionBDTO.setUsingStandards(website);
            airspaceNormsAndConstraintsInformationExtractionBDTO.setConstraintInformation(website);
        }
        else
        {
            airspaceNormsAndConstraintsInformationExtractionBDTO.setUsingStandards(null);
            airspaceNormsAndConstraintsInformationExtractionBDTO.setConstraintInformation(null);
        }

        return Optional.of(airspaceNormsAndConstraintsInformationExtractionBDTO);
    }
    public Optional<AirspaceNormsAndConstraints> informationSave(AirspaceNormsAndConstraintsInformationSaveDTO airspaceNormsAndConstraintsInformationSaveDTO)
    {
        Integer id = airspaceNormsAndConstraintsInformationSaveDTO.getId();
        AirspaceNormsAndConstraints airspaceNormsAndConstraints = airspaceNormsAndConstrainsMapper.selectById(id);
        airspaceNormsAndConstraints.setConstraintInformation(airspaceNormsAndConstraintsInformationSaveDTO.getConstraintInformation());
        airspaceNormsAndConstraints.setUsingStandards(airspaceNormsAndConstraintsInformationSaveDTO.getUsingStandards());
        airspaceNormsAndConstrainsMapper.updateById(airspaceNormsAndConstraints);
        return Optional.of(airspaceNormsAndConstraints);
    }
//    /public Optional<AirspaceNormsAndConstraintsIdPageQueryBDTO> pageFindById(AirspaceNormsAndConstraintsIdPageQueryDTO airspaceNormsAndConstraintsIdPageQueryDTO) {
//        int currentPage = airspaceNormsAndConstraintsIdPageQueryDTO.getCurrentPage();
//        int size = airspaceNormsAndConstraintsIdPageQueryDTO.getSize();
//        Integer id = airspaceNormsAndConstraintsIdPageQueryDTO.getId();
//        Page<AirspaceNormsAndConstraints> page = new Page<>(currentPage, size);
//        Page<AirspaceNormsAndConstraints> airspaceNormsAndConstrainsSearchPage = airspaceNormsAndConstrainsMapper.selectPage(page,null);
//        //搜索后数据处理
//        AirspaceNormsAndConstraintsIdPageQueryBDTO<AirspaceNormsAndConstraintsMini2> airspaceNormsAndConstraintsIdPageQueryBDTO = new AirspaceNormsAndConstraintsIdPageQueryBDTO<>();
//        airspaceNormsAndConstraintsIdPageQueryBDTO.setId(id);
//        airspaceNormsAndConstraintsIdPageQueryBDTO.setTitle(airspaceNormsAndConstrainsMapper.selectById(id).getTitle());
//        airspaceNormsAndConstraintsIdPageQueryBDTO.setUsingStandards(airspaceNormsAndConstrainsMapper.selectById(id).getUsingStandards());
//        airspaceNormsAndConstraintsIdPageQueryBDTO.setConstraintInformation(airspaceNormsAndConstrainsMapper.selectById(id).getConstraintInformation());
//        airspaceNormsAndConstraintsIdPageQueryBDTO.setFileUrl(airspaceNormsAndConstrainsMapper.selectById(id).getFileUrl());
//        List<AirspaceNormsAndConstraintsMini2> airspaceNormsAndConstraintsMini2s= new ArrayList<>();
//        for (AirspaceNormsAndConstraints demand : airspaceNormsAndConstrainsSearchPage.getRecords())
//        {
//            AirspaceNormsAndConstraintsMini2 airspaceNormsAndConstraintsMini2 = new AirspaceNormsAndConstraintsMini2();
//            airspaceNormsAndConstraintsMini2.setId(demand.getId());
//            airspaceNormsAndConstraintsMini2.setTitle(demand.getTitle());
//            airspaceNormsAndConstraintsMini2s.add(airspaceNormsAndConstraintsMini2);
//        }
//        airspaceNormsAndConstraintsIdPageQueryBDTO.setPageData(airspaceNormsAndConstraintsMini2s);
//        airspaceNormsAndConstraintsIdPageQueryBDTO.setImageNum(airspaceNormsAndConstrainsMapper.selectById(id).getImageNum());
//        return Optional.of(airspaceNormsAndConstraintsIdPageQueryBDTO);
//    }
//    //用户需求页面查询
//    public AirspaceNormsAndConstraintsPageQueryBDTO<AirspaceNormsAndConstraintsMini> page(AirspaceNormsAndConstraintsPageQueryDTO airspaceNormsAndConstraintsPageQueryDTO){
//        // 获取分页参数和搜索字符串
//        int currentPage = airspaceNormsAndConstraintsPageQueryDTO.getCurrentPage();
//        int size = airspaceNormsAndConstraintsPageQueryDTO.getSize();
//        String keyText = airspaceNormsAndConstraintsPageQueryDTO.getKeyText();
//        String order = airspaceNormsAndConstraintsPageQueryDTO.getOrder();
//        String informationCategory = airspaceNormsAndConstraintsPageQueryDTO.getInformationCategory();
//
//        QueryWrapper<AirspaceNormsAndConstraints> queryWrapper = new QueryWrapper<>();
//        // 如果传入了 keyText，则对多个字段进行模糊匹// 如果传入了 keyText，则对多个字段进行模糊匹配
//        if(informationCategory != null)
//        {
//            queryWrapper.lambda().eq(AirspaceNormsAndConstraints::getInformationCategory, informationCategory);
//        }
//        else
//        {
//            //不向queryWrapper添加条件如果informationCategory为空
//
//        }
//        if (keyText != null && !keyText.isEmpty()) {
//            queryWrapper.and(e->e.lambda().like(AirspaceNormsAndConstraints::getId, keyText)
//                    .or().like(AirspaceNormsAndConstraints::getTitle, keyText)
//                    .or().like(AirspaceNormsAndConstraints::getPublicationTime, keyText)
//                    .or().like(AirspaceNormsAndConstraints::getInformationSources, keyText));
//        }
//
//        // 根据排序规则决定是按时间最新（降序）还是最晚（升序）
//        if ("时间最新".equals(order)) {
//            queryWrapper.orderByDesc("publication_time");
//        } else if ("时间最晚".equals(order)) {
//            queryWrapper.orderByAsc("publication_time");
//        }
//        // 执行分页查询
//        Page<AirspaceNormsAndConstraints> page = new Page<>(currentPage, size);
//        Page<AirspaceNormsAndConstraints> airspaceNormsAndConstrainsSearchPage = airspaceNormsAndConstrainsMapper.selectPage(page,queryWrapper);
//        //搜索后数据处理
//        int total = (int) airspaceNormsAndConstrainsSearchPage.getTotal();
//        int pageSize = (int)page.getSize();
//
//        List<AirspaceNormsAndConstraintsMini> airspaceNormsAndConstraintsMinis = new ArrayList<>();
//        AirspaceNormsAndConstraintsPageQueryBDTO<AirspaceNormsAndConstraintsMini> airspaceNormsAndConstraintsPageQueryBDTO = new AirspaceNormsAndConstraintsPageQueryBDTO<>();
//
//        // 将查询结果转换为 BDTO
//        for (AirspaceNormsAndConstraints demand : airspaceNormsAndConstrainsSearchPage.getRecords()) {
//            AirspaceNormsAndConstraintsMini airspaceNormsAndConstraintsMini = new AirspaceNormsAndConstraintsMini();
//            airspaceNormsAndConstraintsMini.setId(demand.getId());
//            airspaceNormsAndConstraintsMini.setTitle(demand.getTitle());
//            airspaceNormsAndConstraintsMini.setPublicationTime(demand.getPublicationTime());
//            airspaceNormsAndConstraintsMini.setInformationSource(demand.getInformationSources());
//            airspaceNormsAndConstraintsMini.setInformationCategory(demand.getInformationCategory());
//            airspaceNormsAndConstraintsMinis.add(airspaceNormsAndConstraintsMini);
//        }
//        airspaceNormsAndConstraintsPageQueryBDTO.setTotal(total);
//        airspaceNormsAndConstraintsPageQueryBDTO.setPageData(airspaceNormsAndConstraintsMinis);
//        airspaceNormsAndConstraintsPageQueryBDTO.setPageNum(currentPage);
//        airspaceNormsAndConstraintsPageQueryBDTO.setPageSize(size);
//        Integer pages = (int) Math.ceil((double) total / pageSize);//计算搜寻关键字后的数据总页数
//        airspaceNormsAndConstraintsPageQueryBDTO.setPages(pages);
//        return airspaceNormsAndConstraintsPageQueryBDTO;
//    }
//    public Optional<AirspaceNormsAndConstraintsInformationExtractionBDTO> informationExtraction(AirspaceNormsAndConstraintsInformationExtractionDTO airspaceNormsAndConstraintsInformationExtractionDTO) {
//        Integer id=airspaceNormsAndConstraintsInformationExtractionDTO.getId();
//        Integer currentPage = airspaceNormsAndConstraintsInformationExtractionDTO.getCurrentImage();
//        AirspaceNormsAndConstraints airspaceNormsAndConstraints = airspaceNormsAndConstrainsMapper.selectById(id);
//        AirspaceNormsAndConstraintsInformationExtractionBDTO airspaceNormsAndConstraintsInformationExtractionBDTO = new AirspaceNormsAndConstraintsInformationExtractionBDTO();
//        String websites = airspaceNormsAndConstraints.getFileUrl();
//        String website = null;
//        String currentImageURLJson = airspaceNormsAndConstraints.getFileUrl();
//        if (websites!=null&& !currentImageURLJson.isEmpty()) {
//            List<String> websiteList = Arrays.asList(websites.split(","));
//            website = websiteList.get(currentPage);
//            System.out.println("website:"+website);
//            airspaceNormsAndConstraintsInformationExtractionBDTO.setUsingStandards(website);
//            airspaceNormsAndConstraintsInformationExtractionBDTO.setConstraintInformation(website);
//        }
//        else
//        {
//            airspaceNormsAndConstraintsInformationExtractionBDTO.setUsingStandards(null);
//            airspaceNormsAndConstraintsInformationExtractionBDTO.setConstraintInformation(null);
//        }
//
//        return Optional.of(airspaceNormsAndConstraintsInformationExtractionBDTO);
//    }

//    public Optional<AirspaceNormsAndConstraints> informationSave(AirspaceNormsAndConstraintsInformationSaveDTO airspaceNormsAndConstraintsInformationSaveDTO)
//    {
//        Integer id = airspaceNormsAndConstraintsInformationSaveDTO.getId();
//        AirspaceNormsAndConstraints airspaceNormsAndConstraints = airspaceNormsAndConstrainsMapper.selectById(id);
//        airspaceNormsAndConstraints.setConstraintInformation(airspaceNormsAndConstraintsInformationSaveDTO.getConstraintInformation());
//        airspaceNormsAndConstraints.setUsingStandards(airspaceNormsAndConstraintsInformationSaveDTO.getUsingStandards());
//        airspaceNormsAndConstrainsMapper.updateById(airspaceNormsAndConstraints);
//        return Optional.of(airspaceNormsAndConstraints);
//    }
    public static Pair<Boolean, Object> pdfToImage(PdfToImageDTO pdfToImageDTO) {
        String source = pdfToImageDTO.getSource();
        String desFilePath = pdfToImageDTO.getDesFilePath();
        String desFileName = pdfToImageDTO.getDesFileName();
        String imageType = pdfToImageDTO.getImageType();
        OSSUtil ossUtil = new OSSUtil();
        //通过给定的源路径名字符串创建一个File实例
        File file = new File(source);
        if (!file.exists()) {
            return Pair.of(false, "文件不存在，无法转化");
        }
        //目录不存在则创建目录
        File destination = new File(desFilePath);
        if (!destination.exists()) {
            boolean flag = destination.mkdirs();
            System.out.println("创建文件夹结果：" + flag);
        }
        PDDocument doc = null;
        try {
            //加载PDF文件
            doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            //获取PDF文档的页数
            int pageCount = doc.getNumberOfPages();
            System.out.println("文档一共" + pageCount + "页");
            List<Object> fileList = new ArrayList<>();
            List<String> fileUrlList = new ArrayList<>();
            for (int i = 0; i < pageCount; i++) {
                //只有一页的时候文件名为传入的文件名，大于一页的文件名为：文件名_自增加数字(从1开始)
                String realFileName = pageCount > 1 ? desFileName + "_" + (i + 1) : desFileName;
                String fileName=desFileName;
                if (i==0)
                {
                    String realPdfFileName=fileName+"/"+desFileName + "." + "pdf";
                    String realPdfFilePath=source;
                    String filePdfUrl = ossUtil.upload(realPdfFileName, realPdfFilePath);
                    fileUrlList.add(filePdfUrl);
                }
                //每一页通过分辨率和颜色值进行转化
                BufferedImage bufferedImage = renderer.renderImageWithDPI(i, 96 * 2, ImageType.RGB);
                String filePath = desFilePath + File.separator + realFileName + "." + imageType;
                String realFileImageName=fileName+"/"+realFileName + "." + imageType;
                //写入文件
                ImageIO.write(bufferedImage, imageType, new File(filePath));
                String fileUrl = ossUtil.upload(realFileImageName, filePath);
                //文件名存入list
                fileList.add(filePath);
                fileUrlList.add(fileUrl);
            }
            return Pair.of(true, fileUrlList);
        } catch (IOException e) {
            e.printStackTrace();
            return Pair.of(false, "PDF转化图片异常");
        } finally {
            try {
                if (doc != null) {
                    doc.close();
                }
            } catch (IOException e) {
                System.out.println("关闭文档失败");
                e.printStackTrace();
            }
        }
    }
}
